// 导入类型定义
import { FileType, KnowledgeItem, QuickPhrase, Topic, TranslateHistory } from '@renderer/types'
import { Dexie, type EntityTable } from 'dexie'

// 导入v5版本迁移脚本
import { upgradeToV5 } from './upgrades'

// 定义数据库类型
export const db = new Dexie('CherryStudio') as Dexie & {
  files: EntityTable<FileType, 'id'> // 文件表
  topics: EntityTable<Pick<Topic, 'id' | 'messages'>, 'id'> // 主题表
  settings: EntityTable<{ id: string; value: any }, 'id'> // 设置表
  knowledge_notes: EntityTable<KnowledgeItem, 'id'> // 知识笔记表
  translate_history: EntityTable<TranslateHistory, 'id'> // 翻译历史表
  quick_phrases: EntityTable<QuickPhrase, 'id'> // 快捷短语表
}

// 版本1 - 初始版本只包含files表
db.version(1).stores({
  files: 'id, name, origin_name, path, size, ext, type, created_at, count'
})

// 版本2 - 新增topics和settings表
db.version(2).stores({
  files: 'id, name, origin_name, path, size, ext, type, created_at, count',
  topics: '&id, messages', // &表示主键
  settings: '&id, value'
})

// 版本3 - 新增knowledge_notes表
db.version(3).stores({
  files: 'id, name, origin_name, path, size, ext, type, created_at, count',
  topics: '&id, messages',
  settings: '&id, value',
  knowledge_notes: '&id, baseId, type, content, created_at, updated_at'
})

// 版本4 - 新增translate_history表
db.version(4).stores({
  files: 'id, name, origin_name, path, size, ext, type, created_at, count',
  topics: '&id, messages',
  settings: '&id, value',
  knowledge_notes: '&id, baseId, type, content, created_at, updated_at',
  translate_history: '&id, sourceText, targetText, sourceLanguage, targetLanguage, createdAt'
})

// 版本5 - 添加数据迁移逻辑
db.version(5)
  .stores({
    files: 'id, name, origin_name, path, size, ext, type, created_at, count',
    topics: '&id, messages',
    settings: '&id, value',
    knowledge_notes: '&id, baseId, type, content, created_at, updated_at',
    translate_history: '&id, sourceText, targetText, sourceLanguage, targetLanguage, createdAt'
  })
  .upgrade((tx) => upgradeToV5(tx)) // 执行v5迁移脚本

// 版本6 - 新增quick_phrases表
db.version(6).stores({
  files: 'id, name, origin_name, path, size, ext, type, created_at, count',
  topics: '&id, messages',
  settings: '&id, value',
  knowledge_notes: '&id, baseId, type, content, created_at, updated_at',
  translate_history: '&id, sourceText, targetText, sourceLanguage, targetLanguage, createdAt',
  quick_phrases: 'id'
})

// 导出数据库实例
export default db
